package middlewares

import (
	"boy-go/modules/system/model"
	"boy-go/pkg/response"
	"boy-go/pkg/security"
	"github.com/gin-gonic/gin"
	"net/http"
)

// HasPermission 权限验证
func HasPermission(permission string) func(c *gin.Context) {
	return func(c *gin.Context) {
		loginUser := security.GetLoginUser()
		security.SetPermission(permission)
		if loginUser == nil {
			c.Abort()
			return
		}
		if !model.IsAdmin(&loginUser.UserId) {
			permissions := loginUser.Permissions
			if permissions == nil || len(permissions) == 0 {
				response.AjaxFail(c, http.StatusForbidden, "无权限访问")
				c.Abort()
				return
			}
			if !hasPermissions(permissions, permission) {
				response.AjaxFail(c, http.StatusForbidden, "无权限访问")
				c.Abort()
				return
			}
		}
		c.Next()
	}
}
func hasPermissions(permissions map[string]bool, permission string) bool {
	v, have := permissions[permission]
	if have && v == true {
		return true
	}
	return false
}
